package org.btik.light.mobile.ui.home;

import android.app.AlertDialog;
import android.content.Context;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import org.btik.context.SimpleContext;
import org.btik.light.mobile.MainActivity;
import org.btik.light.mobile.R;
import org.btik.light.mobile.databinding.FragmentHomeBinding;
import org.btik.light.mobile.discovery.ServerInfoPusher;
import org.btik.light.mobile.meta.mo.DefaultDevMo;
import org.btik.light.mobile.platform.util.HttpUtil;
import org.btik.light.mobile.server.MsgCenter;
import org.btik.light.mobile.ui.home.handle.OpenDevPanel;
import org.btik.light.tool.type.StringUtil;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Objects;

import static org.btik.light.mobile.platform.conf.AppConfig.LIGHT_SERVER_HOST;
import static org.btik.light.mobile.platform.conf.AppConfig.NAME_SPACE_LIGHT_HANDLER;
import static org.btik.light.mobile.platform.conf.ContextGlobalNames.MSG_CENTER;
import static org.btik.light.mobile.platform.conf.ContextGlobalNames.SERVER_INFO_PUSHER;
import static org.btik.light.mobile.platform.util.HttpConstant.LIST_DEV;
import static org.btik.light.mobile.platform.util.HttpConstant.URL_BASE;


public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;

    private FragmentHomeBinding binding;

    private View navView;

    private static final int SYNC_CLOUD_MENU_ITEM_ID = 1;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);
        MsgCenter instance = SimpleContext.get(MSG_CENTER);

        instance.regDevListener(homeViewModel);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        setTitle();
        initDevList();
        ServerInfoPusher serverInfoPusher = SimpleContext.get(SERVER_INFO_PUSHER);
        if (serverInfoPusher != null) {
            serverInfoPusher.wakeUp();
        }
        return root;
    }

    private void setTitle() {
        FragmentActivity activity = getActivity();
        Objects.requireNonNull(activity);
        MainActivity mainActivity = (MainActivity) activity;
        String string = mainActivity.getString(R.string.title_home);
        Toolbar toolBar = mainActivity.findViewById(R.id.action_bar);
        toolBar.setTitle(string);

        navView = mainActivity.findViewById(R.id.nav_view);
        if (navView != null) {
            navView.setVisibility(View.VISIBLE);
        }
    }

    private void initDevList() {
        final ListView devList = binding.devList;
        Context context = devList.getContext();
        homeViewModel.initAdaptor(context);
        devList.setAdapter(homeViewModel.getAdapter());
        FragmentManager fragmentManager = getParentFragmentManager();
        homeViewModel.setFragmentManager(fragmentManager);
        devList.setOnItemClickListener(new OpenDevPanel(homeViewModel, this));

    }

    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(@NonNull @NotNull Menu menu, @NonNull @NotNull MenuInflater inflater) {
        menu.add(0, SYNC_CLOUD_MENU_ITEM_ID, 0, "")
                .setIcon(R.drawable.cloud_download)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull @NotNull MenuItem item) {
        if (item.getItemId() == SYNC_CLOUD_MENU_ITEM_ID) {
            String lightServerHost = SimpleContext.get(LIGHT_SERVER_HOST);
            if (lightServerHost.isEmpty()) {
                alert(getString(R.string.can_not_sync_dev), getString(R.string.server_not_set_info));
            } else {
                HttpUtil.doGet(String.format(URL_BASE, lightServerHost, LIST_DEV), this::onDevRefresh);
            }

        }
        return super.onOptionsItemSelected(item);
    }

    private void onDevRefresh(HttpUtil.HttpResponse httpResponse) {
        if (!httpResponse.isSuccess()) {
            String error = httpResponse.getError();
            if (StringUtil.isEmpty(error)) {
                String body = httpResponse.getBody();
                if (!StringUtil.isEmpty(body)) {
                    int bodyLength = body.length();
                    error = body.substring(0, Math.min(128, bodyLength));
                }

            }
            final String errorMsg = "code:" + httpResponse.getCode() + "\n" + error;
            getActivity().runOnUiThread(() -> alert(getString(R.string.can_not_sync_dev), errorMsg));

            return;
        }

        String body = httpResponse.getBody();
        List<DefaultDevMo> defaultDevMos = HttpUtil.parseListJson(body, DefaultDevMo[].class);
        homeViewModel.onDevSync(defaultDevMos);
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        FragmentActivity activity = getActivity();
        activity.runOnUiThread(() -> Toast.makeText(activity, R.string.dev_sync_done, +Toast.LENGTH_SHORT).show());
        RingtoneManager.getRingtone(activity, notification).play();

    }

    private void alert(String title, String message) {
        new AlertDialog.Builder(getActivity())
                .setTitle(title)
                .setMessage(message)
                .setIcon(R.drawable.tip)
                .setNeutralButton(R.string.confirm, (dialogInterface, i) -> {
                })
                .create().show();
    }

    public void hideNav() {
        if (Objects.isNull(navView)) {
            return;
        }
        navView.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        ServerInfoPusher serverInfoPusher = SimpleContext.get(SERVER_INFO_PUSHER);
        if (serverInfoPusher != null) {
            serverInfoPusher.doSendSuspend();
        }
    }
}